package com.bwie.parkdemo.mvvm.model;

import android.content.Context;

import com.bwie.lib_core.base.BaseEntity;
import com.bwie.lib_core.mvvm.base.BaseModel;
import com.bwie.lib_core.network.HttpRetrofitFactory;
import com.bwie.lib_core.network.HttpType;
import com.bwie.parkdemo.dao.LoginUserServe;
import com.bwie.parkdemo.mvvm.model.entity.AddRepairEntity;
import com.bwie.parkdemo.mvvm.model.entity.AddRepairImgEntity;
import com.bwie.parkdemo.mvvm.model.entity.LoginEntity;
import com.bwie.parkdemo.mvvm.model.entity.UploadImgsEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 添加维修申请model
 * 1.图片上传;
 * 2.添加维修;
 * 3.添加维修图片;->由于每一次只能添加一张图片进行绑定
 * ->使用默认封装的request方法进行上传图片绑定；原因
 * 在于默认封装的request方法为一个可变参数，可变参数
 * 相当于数组
 * 4.获取本地用户信息;
 * */
public class AddRepairModel extends BaseModel{
    @Override
    public Observable<BaseEntity> request(RequestBody... bodyes) {
        //全部添加图片请求被观察者
        List<Observable<BaseEntity>>sources = new ArrayList<>();
        for (int i = 0;i < bodyes.length;i ++){
            Observable<AddRepairImgEntity>observable = HttpRetrofitFactory.getInstance()
                    .factory(HttpType.TOKENINTERFACE).getRetrofit()
                    .create(Api.class).requestAddRepairImg(bodyes[i]);
            sources.add(changeOB(observable));
        }
        return Observable.merge(sources);
    }

    //获取本地SQL中缓存的用户信息
    public LoginEntity.Values requestUser(Context ctx){
        return new LoginUserServe(ctx).selUser();
    }

    //添加维修申请
    public Observable<BaseEntity> requestAddRepair(RequestBody body){
        Observable<AddRepairEntity>source = HttpRetrofitFactory.getInstance()
                .factory(HttpType.TOKENINTERFACE).getRetrofit()
                .create(Api.class).requestAddRepair(body);
        return changeOB(source);
    }

    //图片上传
    public Observable<BaseEntity> uploadImg(List<String> list){
        if (list == null)
            return null;
        if (list.size() == 0)
            return null;
        //遍历list生成一个Observable集合
        List<Observable<BaseEntity>>sources=new ArrayList<>();
        for (String path : list){
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),new File(path));
            builder.addFormDataPart("file",path.substring((path.lastIndexOf("/")+1)),body);
            Observable<UploadImgsEntity>ob = HttpRetrofitFactory.getInstance().factory(HttpType.UPLOAD)
                    .getRetrofit().create(Api.class).uploadIms(builder.build().parts());
            sources.add(changeOB(ob));
        }
        return Observable.merge(sources);
    }

    @Override
    public void cleared() {

    }
}
